import re
import csv
import os

skip_pattern = re.compile(r"^[a-z]|#|\.|-|\s")

codes = {}


def build_cangjie(filename):
    f = open(filename, "r")
    for line in f.readlines():
        if skip_pattern.match(line):
            continue
        line = line.rstrip()
        items = line.split("\t")
        character = items[0]
        cangjie = items[1]
        if codes.get(character):
            if codes[character].find(cangjie) > -1:
                continue
            else:
                codes[character] = codes[character] + ";" + cangjie
        else:
            codes[character] = cangjie


def to_fly(s):
    # - erase/^xx$/
    # - derive/^([jqxy])u$/$1v/
    # - derive/^([aoe])([ioun])$/$1$1$2/
    ss = s
    # - xform/^([aoe])(ng)?$/$1$1$2/
    ss = re.sub(r"^([aoe])(ng)?$", r"\1\1\2", ss)
    # - xform/iu$/Q/
    ss = re.sub(r"iu$", "Q", ss)
    # - xform/(.)ei$/$1W/
    ss = re.sub(r"(.)ei$", r"\1W", ss)
    # - xform/uan$/R/
    ss = re.sub(r"uan$", "R", ss)
    # - xform/[uv]e$/T/
    ss = re.sub(r"[uv]e$", "T", ss)
    # - xform/un$/Y/
    ss = re.sub(r"un$", "Y", ss)
    # - xform/^sh/U/
    ss = re.sub(r"^sh", "U", ss)
    # - xform/^ch/I/
    ss = re.sub(r"^ch", "I", ss)
    # - xform/^zh/V/
    ss = re.sub(r"^zh", "V", ss)
    # - xform/uo$/O/
    ss = re.sub(r"uo$", "O", ss)
    # - xform/ie$/P/
    ss = re.sub(r"ie$", "P", ss)
    # - xform/i?ong$/S/
    ss = re.sub(r"i?ong$", "S", ss)
    # - xform/ing$|uai$/K/ss
    ss = re.sub(r"ing$|uai$", "K", ss)
    # - xform/(.)ai$/$1D/
    ss = re.sub(r"(.)ai$", r"\1D", ss)
    # - xform/(.)en$/$1F/
    ss = re.sub(r"(.)en$", r"\1F", ss)
    # - xform/(.)eng$/$1G/
    ss = re.sub(r"(.)eng$", r"\1G", ss)
    # - xform/[iu]ang$/L/
    ss = re.sub(r"[iu]ang$", "L", ss)
    # - xform/(.)ang$/$1H/
    ss = re.sub(r"(.)ang$", r"\1H", ss)
    # - xform/ian$/M/
    ss = re.sub(r"ian$", "M", ss)
    # - xform/(.)an$/$1J/
    ss = re.sub(r"(.)an$", r"\1J", ss)
    # - xform/(.)ou$/$1Z/
    ss = re.sub(r"(.)ou$", r"\1Z", ss)
    # - xform/[iu]a$/X/
    ss = re.sub(r"[iu]a$", "X", ss)
    # - xform/iao$/N/
    ss = re.sub(r"iao$", "N", ss)
    # - xform/(.)ao$/$1C/
    ss = re.sub(r"(.)ao$", r"\1C", ss)
    # - xform/ui$/V/
    ss = re.sub(r"ui$", "V", ss)
    # - xform/in$/B/
    ss = re.sub(r"in$", "B", ss)
    # - xlit/QWRTYUIOPSDFGHJKLZXCVBNM/qwrtyuiopsdfghjklzxcvbnm/
    ss = ss.lower()
    # print(s, ss)
    return ss


def build_characters(filename):
    basename = os.path.basename(filename)
    f = open(filename, "r")
    with open("cn_dicts/" + basename, "w", newline="") as csvfile:
        dict_writer = csv.writer(csvfile, delimiter="\t")
        dict_writer.writerow(["# Rime dictionary"])
        dict_writer.writerow(["# encoding: utf-8"])
        dict_writer.writerow(["#"])
        dict_writer.writerow(["---"])
        dict_writer.writerow(["name: "+basename])
        dict_writer.writerow(['version: "1.1"'])
        dict_writer.writerow(['sort: by_weight'])
        dict_writer.writerow(["..."])
        dict_writer.writerow([""])
        for line in f.readlines():
            if skip_pattern.match(line):
                continue
            line = line.rstrip()
            [character, pinyin, weight] = line.split("\t")
            flypy = to_fly(pinyin)
            try:
                cangjie = codes[character]
            except KeyError:
                print(character)
                continue
            for i in cangjie.split(';'):
                dict_writer.writerow([character, flypy+'['+i, weight])


def build_words(filename):
    basename = os.path.basename(filename)
    f = open(filename, "r")
    with open("cn_dicts/" + basename, "w", newline="") as csvfile:
        dict_writer = csv.writer(csvfile, delimiter="\t")
        dict_writer.writerow(["# Rime dictionary"])
        dict_writer.writerow(["# encoding: utf-8"])
        dict_writer.writerow(["#"])
        dict_writer.writerow(["---"])
        dict_writer.writerow(["name: "+basename])
        dict_writer.writerow(['version: "1.1"'])
        dict_writer.writerow(['sort: by_weight'])
        dict_writer.writerow(["..."])
        dict_writer.writerow([""])
        for line in f.readlines():
            if skip_pattern.match(line):
                continue
            line = line.rstrip()
            [character, pinyin, weight] = line.split("\t")
            flypys = [to_fly(s) for s in pinyin.split(' ')]
            flypy = ' '.join(flypys)
            dict_writer.writerow([character, flypy, weight])


build_cangjie("./cangjie_dicts/cangjie5.dict.yaml")
build_cangjie("./cangjie_dicts/2022.dict.yaml")
build_cangjie("./cangjie_dicts/buchong.dict.yaml")

build_characters("./rime-frost/cn_dicts/8105.dict.yaml")
build_characters("./rime-frost/cn_dicts/41448.dict.yaml")


build_words("./rime-frost/cn_dicts/base.dict.yaml")
build_words("./rime-frost/cn_dicts/ext.dict.yaml")
build_words("./rime-frost/cn_dicts/tencent.dict.yaml")
build_words("./rime-frost/cn_dicts/others.dict.yaml")
